package com.bean;

import com.constant.AppConstant;
import com.dto.VersionDto;
import com.entity.SysServerAndPackageVersion;
import com.exception.ParamException;
import com.repository.*;
import com.service.VersionService;
import com.utils.SFTPUtil;
import com.utils.WindowsFtpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;

import java.io.File;
import java.util.List;

@Configuration      //1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling
@Slf4j// 2.开启定时任务
public class DynamicScheduleTask implements SchedulingConfigurer {


    @Autowired
    @SuppressWarnings("all")
    private CronRepository cronRepository;

    @Autowired
    private SysServerRepository serverRepository;

    @Autowired
    private SysDeployHistoryRepository sysDeployHistoryRepository;

    @Autowired
    private VersionService service;
    @Autowired
    private SysServerAndPackageVersionRepository sysServerAndPackageVersionRepository;

    @Autowired
    private SysVersionRepository sysVersionRepository;

    /**
     * 执行定时任务.
     */
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {

        taskRegistrar.addTriggerTask(
                //1.添加任务内容(Runnable)
                () -> {
                    try {
                        List<VersionDto> all = service.findAll();
                        for (int i = 0; i < all.size(); i++) {
                            Boolean aBoolean = all.get(i).getAppRemoteDevelopment();
                            if (aBoolean) {
                                SysServerAndPackageVersion byDeployIdInServer = sysServerAndPackageVersionRepository.findByDeployIdInServer(all.get(i).getDeployId());

                                if (byDeployIdInServer != null) {
                                    SFTPUtil sftpUtil = new SFTPUtil(serverRepository.findById(byDeployIdInServer.getServerId()).get().getServerUserName(), serverRepository.findById(byDeployIdInServer.getServerId()).get().getServerPassword(), serverRepository.findById(byDeployIdInServer.getServerId()).get().getServerIp(), serverRepository.findById(byDeployIdInServer.getServerId()).get().getServerPort());
                                    sftpUtil.login();
                                    log.info("开始连接");
                                    sftpUtil.upload1("D:" + File.separator + "testb", AppConstant.DEFAULT_SAVE_PATH, AppConstant.DEFAULT_FLAG);
                                    WindowsFtpUtils.sshServer(serverRepository.findById(byDeployIdInServer.getServerId()).get().getServerIp(), serverRepository.findById(byDeployIdInServer.getServerId()).get().getServerPort(), serverRepository.findById(byDeployIdInServer.getServerId()).get().getServerUserName(), serverRepository.findById(byDeployIdInServer.getServerId()).get().getServerPassword(), AppConstant.DEFAULT_COMMAND);
                                    sftpUtil.logout();
                                    log.info("关闭连接");
                                    if (sysDeployHistoryRepository.findByAppName(all.get(i).getAppName()) > 0 && sysVersionRepository.getByAppName(all.get(i).getAppCurrentVersion(), all.get(i).getDeployId(), all.get(i).getAppOwner()) > 0) {
                                        log.info("更新成功");
                                    } else {
                                        throw new ParamException("更新失败");
                                    }
                                }

                            }
                        }
                    } catch (Exception e) {
                        throw new ParamException(e.getMessage());
                    }
                },
                //2.设置执行周期(Trigger)
                triggerContext -> {
                    //2.1 从数据库获取执行周期
                    String cron = cronRepository.getCron();
                    //2.2 合法性校验.
                    if (StringUtils.isEmpty(cron)) {
                        // Omitted Code ..
                    }
                    //2.3 返回执行周期(Date)
                    return new CronTrigger(cron).nextExecutionTime(triggerContext);
                }
        );
    }
}
